import { GetServerSideProps } from "next"
import { Post, Book } from "../../../types"
import dayjs from "dayjs"
import PageLayout from "../../../segments/PageLayout"
import BookTocBlock from "../../../segments/BookTocBlock"

import { getBookByPath } from "../../../server/app/BookService"
import { findPostByKey } from "../../../server/app/PostService"

const PostPage: React.FC<{ bookPath: string; postPath: string; post: Post; book: Book }> = ({
  bookPath,
  post,
  book,
}) => {
  const tocBlock = <BookTocBlock book={book} title={book.title} titleUrl={`/b/${bookPath}`} />
  return (
    <PageLayout>
      <div className="post-layout">
        <div className="left">{tocBlock}</div>
        <div className="post">
          <h1>{post.title}</h1>
          <small style={{ color: "gray" }}>
            {post.authorName} 创建于{dayjs(post.createTime).format("YYYY年M月D日")}
          </small>
          <div style={{ margin: "1rem 0", userSelect: "none" }}>
            <img src="/assets/separator.png" alt="sep" style={{ width: "100%" }} />
          </div>
          {(() => {
            switch (post.type) {
              case "adoc":
                return <div className="adoc" dangerouslySetInnerHTML={{ __html: post.body }} />
              default:
                return <div>暂不支持的文档类型:{post.type}</div>
            }
          })()}
        </div>
        <div className="right">TODO:</div>
      </div>
      <div className="post-mobile-toc">{tocBlock}</div>
    </PageLayout>
  )
}

export default PostPage

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const { bookPath, postPath } = ctx.params || {}
  const [book, post] = await Promise.all([
    getBookByPath(bookPath as string),
    findPostByKey(postPath as string),
  ])

  if (!book || !post) {
    return { notFound: true }
  } else {
    return { props: { bookPath, postPath, post, book } }
  }
}
